import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/un_bound_commodity_list_data.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class BindingCommodityProvider extends ChangeNotifier {
  UnBoundCommodityData data;
  String keyword = '';

  List<Commodity> get commoditys => data.commodityList.where((item) => Utils.matchChineseWordWithPinyin(item.title, keyword)).toList();

  Future<Result<UnBoundCommodityData>> initData() async {
    try {
      var res = await api.queryUnBoundCommodityList();
      if (!res.successful()) {
        return Result.error(res.msg);
      }

      data = res.data;
      notifyListeners();

      return Result.value(res.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  binding(Commodity commodity) async {
    try {
      showLoadingToast();

      var res = await api.bindCommodity(commodity.id);
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('关联成功');

      data.commodityList.remove(commodity);
      data.bindCount += 1;

      notifyListeners();
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  bindingAll() async {
    try {
      showLoadingToast();

      var res = await api.bindCommodityAll();
      if (!res.successful()) {
        toast(res.msg);
        return;
      }

      toast('关联成功');

      data.bindCount += data.commodityList.length;
      data.commodityList = [];

      notifyListeners();
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  setSearchWord(String value) {
    keyword = value;
    notifyListeners();
  }
}
